package br.ucb.ucblive.HIB;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.sql.JoinType;

import br.ucb.ucblive.beans.Moderador;
import br.ucb.ucblive.beans.Usuario;

public class UsuarioHIB {

	@SuppressWarnings("unchecked")
	public List<Usuario> listar() {
		Session session = HibernateUtil.getSession();
		try {
			return session.createCriteria(Usuario.class).list();
		} finally {
			session.close();
		}
	}	
	
	public void salvar(Usuario obj) {
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		session.saveOrUpdate(obj);
		transaction.commit();
		session.close();
	}
	
	public void excluir(Usuario obj) throws ConstraintViolationException {
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(obj);
		transaction.commit();
		session.close();
	}
	
	
	public Usuario consultar(String login) {
		Session session = HibernateUtil.getSession();
		try {
			Usuario obj = (Usuario) session.get(Usuario.class,login);
			return obj;
		} finally {
			session.close();
		}
	}

	public Moderador consultarModeradorByUsuario(String login) {
		Session session = HibernateUtil.getSession();
		try {
			Moderador obj = (Moderador) session.createCriteria(Moderador.class).
				   add(Restrictions.eq("usuario.login", login)).
				   setMaxResults(1).
				   uniqueResult();
			return obj;
		} finally {
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Usuario> listarLessAdministrador() {
		Session session = HibernateUtil.getSession();
		try {
			return session.createCriteria(Usuario.class).
					add(Restrictions.not(Restrictions.eq("tipo", 4))).
					list();
		} finally {
			session.close();
		}
	}
	
	public Usuario consultarUsuarioByMatricula(String matricula) {
		Session session = HibernateUtil.getSession();
		try {
			Usuario obj = (Usuario) session.createCriteria(Usuario.class).
					createAlias("moderador", "moderador", JoinType.LEFT_OUTER_JOIN).
					createAlias("professor", "professor", JoinType.LEFT_OUTER_JOIN).
					createAlias("aluno", "aluno", JoinType.LEFT_OUTER_JOIN).
				    add(Restrictions.or(
				    		Restrictions.or(
				    			Restrictions.eq("moderador.matricula", matricula), Restrictions.eq("professor.matricula", matricula)), 
				    					Restrictions.eq("aluno.matricula", matricula)
				    		)
				    	).
				   setMaxResults(1).
				   uniqueResult();
			return obj;
		} finally {
			session.close();
		}
	}
}
